package com.farshine.baokan.box;


import org.omg.CORBA.Environment;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Date;

public class SendCommand {

    private static final int SPLIT_TIME = 10;

    private Socket client = null;
    private InputStream s_in;
    private OutputStream s_out;

    private int lastSendAddr = 0;
    private long lastSendTime = 0;

    public boolean open(String server, int port) {
        try {
            client = new Socket(server, port);
            client.setSoTimeout(1000);
            s_in = client.getInputStream();
            s_out = client.getOutputStream();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void close() {
        if (client!=null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            client = null;
        }
    }

    public boolean send(byte[] data) {
        if (client==null) return false;

        try {
            //判断上个设备，同一个设备发送间隔
            int addr = data[1] | (data[2] << 8);
            if (addr==lastSendAddr) {
                long dt = new Date().getTime() - lastSendTime;
                if (dt<SPLIT_TIME) {
                    Thread.sleep(SPLIT_TIME - dt);
                }
            } else {
                lastSendAddr = addr;
            }
        } catch (Exception ex) {

        }

        try {
            s_out.write(data);
            System.out.println("Send: " + new String(data));
            lastSendTime = new Date().getTime();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public byte[] read() {
        if (client==null) return new byte[0];

        byte[] data = new byte[256];
        try {
            int len = 0;
            do {
                len += s_in.read(data, len, data.length-len);
            }while (len>0 && len<12);
            if (len==0) return new byte[0];

            System.out.println("Recv: " + new String(data, 0, len));

            byte[] buf = new byte[len];
            System.arraycopy(data, 0, buf, 0, len);
            return buf;
        } catch (SocketTimeoutException e1) {
          //超时，应该是箱头不存在，不处理
            System.out.println("超时。");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }
}
